import Axios from "axios";
import qs from "qs";
import Vue from "vue";
import sm4 from "./sm4";
import { Toast, Notify } from "vant";
import { xsfasd, encodeByHexSMS4, decodeByHexSMS4 } from "./RequestUtil"
import router from "@/router/index"
class Http {
    isEncryption =  JSON.parse(process.env.VUE_APP_IS_ENCRYPTION);
    requestURL = process.env.VUE_APP_REMOTE_BASE_URL;
    static instance() {
        return new Http();
    }
    async postJSON(data, oresolve, oreject) {
        const obj = {
            autoShowWait: true,
        };
        data = Object.assign(obj, data);
        if (data["autoShowWait"] == true) {
            Toast.loading({
                duration: 0,
                message: "加载中...",
                forbidClick: true,
            });
        }
        if (data["defineRequesetWay"]) {

        }else {
            if (process.env.VUE_APP_USE_PLATFORM && JSON.parse(process.env.VUE_APP_USE_PLATFORM) == true) {
                data["defineRequesetWay"] = 'pluginRequest';
            }else {
                data["defineRequesetWay"] = 'ajaxRequest';
            }
        }
        const commonParam = data["params"];
        if (!commonParam) {
            return new Promise.reject("");
        }
        return new Promise((resolve, reject) => {
            /// 如果原生请求方法可用
            if (data["defineRequesetWay"] == 'pluginRequest') {
                const tempData = data;
                if (deviceReady == true) {
                    const that = this;
                    if (commonParam != null) {
                        console.log("---请求:" + that.getLogTime() + "入参：" + JSON.stringify(commonParam));
                    }
                    navigator.ajax.postJSON(process.env.VUE_APP_APPCODE, commonParam, process.env.VUE_APP_APPSERVERCODE,
                        (result) => {
                            if (data["autoShowWait"]) {
                                Toast.clear();
                            }

                            if (result != null && that.showLog(data["data"]["route"])) {
                                console.log("--------响应:" + that.getLogTime() + "入参：" + JSON.stringify(commonParam) + "-----" + "出参：" + JSON.stringify(result));
                            }
                            if (oresolve && oreject) {
                                that.handleBack(oresolve, oreject, result, commonParam);
                                return;
                            }
                            that.handleBack(resolve, reject, result, commonParam);
                        },
                        (err) => {
                            reject(err);
                        }
                    );
                } else {
                    setTimeout(() => {
                        Http.instance().postJSON(tempData, resolve, reject);
                    }, 1000);
                }
            } else {
                var Url = `${this.requestURL}${data["url"]}`;
                var token = this.getToken();
                var config = {
                    method: "post",
                    url: Url,
                    data: commonParam,
                    headers: {
                        "Content-Type": "application/json",
                        "token": token,
                    },
                };
                Axios(config)
                    .then((result) => {
                        console.log("返回结果：" + JSON.stringify(result));
                        if (data["autoShowWait"]) {
                            Toast.clear();
                        }
                        this.handleBack(resolve, reject, result["data"], commonParam);
                    })
                    .catch((err) => {
                        console.log("-------------响应异常：" + JSON.stringify(err));
                        Toast.clear();
                        if(err && err['message'] == "Network Error"){
                            err['message'] = "网络异常，请检查网络";
                        }
                        reject(err);
                    });
            }
        });
    }

    handleBack(resolve, reject, data, commonParam) {
        console.log("处理结果：" + JSON.stringify(data))
        if (data && data["code"] == 0) {
            resolve(data);
        } else if (data && data["code"] == 401) {
            Notify({
                message: "登陆信息已失效， 请重新登陆",
                type: 'danger',
            });
            //{"msg":"token失效，请重新登录","code":401}
            if("token失效，请重新登录" == data["msg"] ||  "invalid token" == data["msg"]){
                localStorage.removeItem("userContextStr");
                router.replace({ name: 'Login' });
            }else {
                reject(data['msg']);
            }
        } else if (data && data["code"] == 500) {
            reject(data['msg']);
        } else {
            console.log("服务异常");
            reject("服务出错了，请稍后再试或者联系运维人员");
            Notify({
                message: data["msg"],
                type: 'danger',
            });
        }
    }

    routeObj = {
        'qxgl': "QxlcManagerController,DefectManageController,DeviceController,FileUploadController",
        "common": 'CommonController,AppEntranceController',
        'task': 'TourPlanController',
        'yhgl': 'YhglController'
    }
    getToken() {
        var userContextStr = localStorage.getItem("userContextStr");
        if(userContextStr != null && userContextStr != ""){
            var userContext = JSON.parse(userContextStr);
            return userContext.token;
        }else {
            return "";
        }
        
    }

    getLogTime() {
        var nowtime = new Date();
        var year = nowtime.getFullYear();
        var month = nowtime.getMonth() + 1;
        var date = nowtime.getDate();
        var showTime =
            year + "-" + month + "-" + date + " " + nowtime.toLocaleTimeString();
        return "" + showTime;
    }
    showLog(url) {
            if (
                "TrailManageController_recordPersonTrail,CommonController_getUserInfoByToken".includes(
                    url
                )
            ) {
                return false;
            }
            return true;
        }
    formatImgPath = new Uploader().formatImgPath;

    // 解压缩数据
    unzip(b64Data) {
        var strData = atob(b64Data);
        // Convert binary string to character-number array
        var charData = strData.split('').map(function(x) {
            return x.charCodeAt(0);
        });
        // Turn number array into byte-array
        var binData = new Uint8Array(charData);
        // // unzip
        var data = pako.inflate(binData);
        // Convert gunzipped byteArray back to ascii string:
        strData = this.Utf8ArrayToStr(data)
        return strData;
    }

    //解决数据过大和中文乱码
    Utf8ArrayToStr(array) {
        var out, i, len, c;
        var char2, char3;

        out = "";
        len = array.length;
        i = 0;
        while (i < len) {
            c = array[i++];
            switch (c >> 4) {
                case 0:
                case 1:
                case 2:
                case 3:
                case 4:
                case 5:
                case 6:
                case 7:
                    // 0xxxxxxx
                    out += String.fromCharCode(c);
                    break;
                case 12:
                case 13:
                    // 110x xxxx   10xx xxxx
                    char2 = array[i++];
                    out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
                    break;
                case 14:
                    // 1110 xxxx  10xx xxxx  10xx xxxx
                    char2 = array[i++];
                    char3 = array[i++];
                    out += String.fromCharCode(((c & 0x0F) << 12) |
                        ((char2 & 0x3F) << 6) |
                        ((char3 & 0x3F) << 0));
                    break;
            }
        }
        return out;
    }
}

class Uploader {
    async upload(data, sureBack, failBack) {
        if (data["autoShowWait"]) {
            Toast.loading({
                duration: 0,
                message: "上传中...",
                forbidClick: true,
            });
        }
        let uploadUrl = process.env.VUE_APP_REMOTE_BASE_URL + "/makeFriends/sys/oss/uploadLocal";
        
        let fileName = data["fileName"];
        var file = this.dataURLtoFile(data["base64URL"], fileName);

        var userContextStr = localStorage.getItem("userContextStr");
        var userContext = JSON.parse(userContextStr);
        var token=  userContext['token'];

        let tformData = new FormData();
        // tformData.append("file", file );
        //带文件名称， 后端生成文件带后缀
        tformData.append("file", file , data.fileName);
        tformData.append("saou", data["moduleName"]);
        tformData.append("platform", "1");
        tformData.append("token", token);
        if (process.env.VUE_APP_SYSTEM_ENVIRONMENT == "dlydt") {
            console.log("输电调用i国网上传文件插件");
            navigator.ajax.postFile(function(result) {
                    //成功回调
                    // result = {"gmmsResult":"true","businessRes":"/app/oss/download/E3634BBE5E8B4E2620230427162LPXTA229DF883567B249","gmmsMsg":"上传成功"}
                    console.log("上传业务回调");
                    if (data["autoShowWait"]) {
                        Toast.clear();
                    }
                    var ret = result;
                    ret["url"] = ret["businessRes"];
                    sureBack && sureBack(ret);
                },
                function(msg) {
                    //失败回调
                    console.log('前端失败接收数据：' + msg)
                    failBack && failBack(msg);
                }, {
                    //文件对象
                    file: file,
                    //申请的文件上传key
                    saou: uploadSaou,
                    //用户登录token值
                    gmmsToken: token,
                });
        } else {
            console.log("Axios调用上传文件地址：" + uploadUrl);
            Axios.post(`${uploadUrl}`, tformData, {
                    headers: {
                        "Content-Type": "multipart/form-data",
                        "token": token,
                    },
                })
                .then((result) => {
                    console.log("上传图片成功响应：" + JSON.stringify(result));
                    if(result['status'] == 200 && result['data'] && result['data']['code'] == 0){
                        var serveResult = result['data'];
                        // serveResult = {"msg":"/api/company2/fetch/dmjaco3kz1slu76z2x4n","code":0};
                        serveResult['url'] = serveResult['msg'];
                        if (data["autoShowWait"]) {
                            Toast.clear();
                        }
                        sureBack && sureBack(serveResult);
                    }else {
                        failBack && failBack(result);
                    }
                })
                .catch((err) => {
                    console.log("上传图片错误响应：" + JSON.stringify(err));
                    failBack && failBack(err);
                });

        }


    }

    /**
     * 多图上传
     * @param dataList 数据源
     * @param sureBack 成功回调
     */
    multiUpload(dataList, sureBack, autoShowWait, failCallBack) {
        if (autoShowWait) {
            Toast.loading({
                duration: 0,
                message: "加载中...",
                forbidClick: true,
            });
        }
        // 每次多图上传队列置空
        this.uploadedList = [];

        if (dataList.length == 0) {
            sureBack && sureBack([]);
            return;
        }
        for (var i = 0; i < dataList.length; i++) {
            // 闭包图片上传
            var doUPload = (data, i, length, sureBack) => {
                this.upload({
                        ...data,
                        fileName: data["fileName"] || `${new Date().getTime()}${parseFloat(randomFloat().toFixed(4)) * 10000}`,
                        base64URL: data["base64URL"],
                        moduleName: data["moduleName"],
                    },
                    (ret) => {
                        if (ret && ret["url"]) {
                            this.uploadedList[i] = ret["url"];
                            // 上传队列长度不足，不比对
                            if (this.uploadedList.length < length) {
                                return;
                            }
                            // 上传队列结果判空
                            var success = true;
                            for (let item of this.uploadedList) {
                                if (!item || item.length == 0) {
                                    success = false;
                                }
                            }
                            // 队列上传成功，返回
                            if (success) {
                                Toast.clear();
                                sureBack && sureBack(this.uploadedList);
                            }
                        }
                    },
                    (ret) => {
                        // 上传失败重新上传
                        // doUPload(data, i, length, sureBack);
                        Toast.clear();
                        failCallBack && failCallBack(ret);
                    }
                );
            };
            doUPload(dataList[i], i, dataList.length, sureBack);
        }
    }

    formatImgPath(imgPath) {
            if (!imgPath) {
                return;
            }
            var downloadPath = process.env.VUE_APP_REMOTE_BASE_URL + "/makeFriends";

            imgPath = downloadPath + imgPath;
            console.log("下载路径：" + imgPath);
            return imgPath;
            // 安全， 下载是否要串参数
            // const token = Http.instance().getToken();
            // var suffix = '?saou=SG5oZmtXQ3BhOGwvTlNmV2NYWitCdz09&platform=' + platform + '&gmmsToken=' + token;
            // // console.log(prefix + imgPath.substring(imgPath.indexOf('/app/oss/')) + suffix)
            // if (imgPath != null && imgPath.indexOf('/app/oss/') > -1) {
            //     if (process.env.VUE_APP_SYSTEM_ENVIRONMENT == 'dlydt') {
            //         var igwFileDownLoadURL = sessionStorage.getItem("igwFileDownLoadURL");
            //         var result = igwFileDownLoadURL + imgPath.substring(imgPath.indexOf('/app/oss/')) + suffix;
            //         console.log("i国网图片地址：" + result);
            //         return result;
            //     } else {
            //         return prefix + imgPath.substring(imgPath.indexOf('/app/oss/')) + suffix
            //     }

            // }
            // return imgPath;
        }

    dataURLtoFile(dataURI, type) {
        let binary = atob(dataURI.split(",")[1]);
        let array = [];
        for (let i = 0; i < binary.length; i++) {
            array.push(binary.charCodeAt(i));
        }
        return new Blob([new Uint8Array(array)], {
            type: "image/png",
        });
    }
    async dataURLtoBlob(dataurl) {
        const arr = dataurl.split(",");
        const mime = arr[0].match(/:(.*?);/)[1];
        const bstr = atob(arr[1]);
        let n = bstr.length;
        const u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
        }

        return new Blob([u8arr], {
            type: mime,
        });
    }
    async uploadFile(data, sureBack, failBack) {
        if (!Vue.prototype.$dealMsg("UPLOAD_URL")) {
            sureBack &&
                sureBack({
                    url: "",
                });
            return;
        }
        if (data["autoShowWait"]) {
            Toast.loading({
                duration: 0,
                message: "加载中...",
                forbidClick: true,
            });
        }
        // -----------------穿透开发临时代码---------------------------------------------

        var uploadObj = Vue.prototype.$dealMsg("UPLOAD_URL") ?
            JSON.parse(Vue.prototype.$dealMsg("UPLOAD_URL")) : {};
        // -----------------穿透开发临时代码---------------------------------------------
        //获取密钥
        var uploadSaou = uploadObj.saou;
        if (data.moduleName && this.moduleNameObj[data.moduleName]) {
            data["saouKey"] = this.moduleNameObj[data.moduleName];
        }
        if (data["saouKey"] && uploadObj[data["saouKey"]]) {
            uploadSaou = uploadObj[data["saouKey"]];
        }
        let uploadUrl = uploadObj.url;
        // let uploadUrl = "http://sjtd0okmht5.epgis.com:19002/mdyj/app/oss/upload";
        uploadUrl = uploadUrl + "/app/oss/upload";
        var file = data["file"];

        let tformData = new FormData();
        tformData.append("file", file);
        console.log("saouKey:" + data["saouKey"], uploadSaou, data.moduleName);
        tformData.append("saou", uploadSaou);
        const platform = process.env.VUE_APP_SYSTEM_ENVIRONMENT == "dlydt" ? 1 : 2;
        tformData.append("platform", platform);
        const token = Http.instance().getToken();
        tformData.append("gmmsToken", token);

        if (process.env.VUE_APP_SYSTEM_ENVIRONMENT == "dlydt") {
            console.log("输电调用i国网上传文件插件");
            navigator.ajax.postFile(function(result) {
                    //成功回调
                    // result = {"gmmsResult":"true","businessRes":"/app/oss/download/E3634BBE5E8B4E2620230427162LPXTA229DF883567B249","gmmsMsg":"上传成功"}
                    console.log("上传业务回调");
                    if (data["autoShowWait"]) {
                        Toast.clear();
                    }
                    var ret = result;
                    ret["url"] = ret["businessRes"];
                    sureBack && sureBack(ret);
                },
                function(msg) {
                    //失败回调
                    console.log('前端失败接收数据：' + msg)
                    failBack && failBack(msg);
                }, {
                    //文件对象
                    file: file,
                    //申请的文件上传key
                    saou: uploadSaou,
                    //用户登录token值
                    gmmsToken: token,
                });
        } else {
            Axios.post(`${uploadUrl}`, tformData, {
                    headers: {
                        "Content-Type": "multipart/form-data",
                    },
                })
                .then((result) => {
                    let ret = result.data;
                    Toast.clear();
                    ret["url"] = ret["url"];

                    sureBack && sureBack(ret);
                })
                .catch((err) => {
                    failBack && failBack(err);
                });

        }

    }
}

function randomFloat() {
    // 生成 32 位随机值
    const fooArray = new Uint32Array(1);
    // 最大值是 2^32 –1
    const maxUint32 = 0xffffffff;
    // 用最大可能的值来除
    return crypto ? crypto.getRandomValues(fooArray)[0] / maxUint32 : 0.5;
}



export { Http, Uploader };